package com.example.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.LinkedHashMap;
import java.util.Map;
@SuppressWarnings("all")
public class BeanUtils {
    /**
     * JavaBean转Map
     *
     * @param obj
     * @return
     */
    public static Map<String, Object> bean2Map(Object obj) {
        Map<String, Object> map = new LinkedHashMap<>();
        Class<?> clazz = obj.getClass();
        if (obj instanceof Map) {
            return (Map<String,Object>)obj;
        }
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            String fieldName = field.getName();
            Object value = null;
            try {
                value = field.get(obj);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            if (value == null) {
                value = "";
            }
            map.put(fieldName, value);
        }
        return map;
    }

    /**
     * Map转JavaBean
     *
     * @param clazz
     * @param map
     * @param <T>
     * @return
     */
    public static <T> T map2Bean(final Class<T> clazz, final Map<String, ? extends Object> map) {
        if (map == null) {
            return null;
        }
        T res = null;
        try {
            res = clazz.getDeclaredConstructor().newInstance();
            //获取到所有属性，不包括继承的属性
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                //获取字段的修饰符
                int mod = field.getModifiers();
                if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
                    continue;
                }
                //设置对象的访问权限
                field.setAccessible(true);
                //根据属性名称去map获取value
                if (map.containsKey(field.getName())) {
                    //给对象赋值
                    field.set(res, map.get(field.getName()));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }

}

